import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { BookTagEntity } from '../entities/book-tag.entity'
import { CreateBookTagDto } from '../dto/create-book-tag.dto'
import { UpdateBookTagDto } from '../dto/update-book-tag.dto'
import { QueryBookTagDto } from '../dto/query-book-tag.dto'

@Injectable()
export class BookTagService {
  constructor(
    @InjectRepository(BookTagEntity)
    private readonly bookTagRepository: Repository<BookTagEntity>,
  ) {}

  async create(createBookTagDto: CreateBookTagDto) {
    const bookTag = this.bookTagRepository.create(createBookTagDto)
    return await this.bookTagRepository.save(bookTag)
  }

  async findAll(queryBookTagDto: QueryBookTagDto) {
    const { tagName } = queryBookTagDto
    const queryBuilder = this.bookTagRepository.createQueryBuilder('bookTag')
      .where('bookTag.isDelete = :isDelete', { isDelete: 0 })

    if (tagName) {
      queryBuilder.andWhere('bookTag.tagName LIKE :tagName', { tagName: `%${tagName}%` })
    }

    return await queryBuilder.getMany()
  }

  async findOne(id: number) {
    return await this.bookTagRepository.findOne({ where: { id, isDelete: 0 } })
  }

  async update(id: number, updateBookTagDto: UpdateBookTagDto) {
    const bookTag = await this.findOne(id)
    if (!bookTag) {
      return null
    }

    Object.assign(bookTag, updateBookTagDto)
    return await this.bookTagRepository.save(bookTag)
  }

  async remove(id: number) {
    const bookTag = await this.findOne(id)
    if (!bookTag) {
      return null
    }

    bookTag.isDelete = 1
    return await this.bookTagRepository.save(bookTag)
  }
} 